package Net.tcp.loagin;

import java.io.*;
import java.net.Socket;

/**
 * 模拟登陆：多次访问
 * 创建客户端
 * 1.建立链接 使用Socket创建客户端+服务器的地址和端口
 * 2.操作：输入输出流操作
 * 3.释放资源
 */
public class LoginMoreClient {
    public static void main(String[] args) throws IOException {
        System.out.println("----Client----");

        //1.建立链接 使用Socket创建客户端+服务器的地址和端口
        Socket client = new Socket("localhost",8888);
        //2.操作：输入输出流操作
        new Send(client).send();
        new Receive(client).receive();
        //接收结果

        //3.释放资源
//        dis.close();
//        dos.close();
        client.close();
    }

    static class Send{
        private Socket client;
        private DataOutputStream dos;
        private BufferedReader console;
        String msg;
        public  Send(Socket client){
            this.client= client;
            console = new BufferedReader(new InputStreamReader(System.in));
            this.msg=init();
            try {
                this.dos = new DataOutputStream(client.getOutputStream());//getOutputStream返回此套接字的输出流。
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public String init(){

            try {
                System.out.println("请输入用户名");
                String uname = console.readLine();
                System.out.println("请输入密码");
                String password = console.readLine();
                return "uname="+uname+"&password="+password;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }

        public void send(){
            try {
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class Receive{
        private Socket client;
        private DataInputStream dis;
        public Receive(Socket client){
            this.client=client;
            try {
                this.dis = new DataInputStream(client.getInputStream());//getInputStream返回此套接字的输入流。
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void receive(){
            try {
                String result = dis.readUTF();
                System.out.println(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
